package org.wat.wcy.isi.mmazur.bp.io.xpdl.processors;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.wat.wcy.isi.mmazur.bp.io.model.GraphicsInfo;
import org.wat.wcy.isi.mmazur.bp.io.model.IdDesc;
import org.wat.wcy.isi.mmazur.bp.io.model.Node;
import org.wat.wcy.isi.mmazur.bp.io.model.Transition;
import org.wat.wcy.isi.mmazur.bp.io.model.enums.NodeType;
import org.wat.wcy.isi.mmazur.bp.io.model.temporary.Route;
import org.wat.wcy.isi.mmazur.bp.io.xpdl.IXMLProcessor;
import org.xml.sax.Attributes;

public class ArtifactsProcessor implements IXMLProcessor {

	private Node currentNode;
	private Map<String, Node> nodes;
	
	public ArtifactsProcessor() {
		nodes = new HashMap<String, Node> ();
	}
	
	@Override
	public void startElement(String name, Attributes attr) {
		if (StringUtils.equals(name, "/Package/Artifacts/Artifact")) {
			currentNode = new Node();
			String id = attr.getValue("Id");
			String artifactType = attr.getValue("ArtifactType");
			NodeType type = NodeType.valueOf(artifactType.toUpperCase());
			if (type == NodeType.ANNOTATION) {
				String textAnnotation = attr.getValue("TextAnnotation");
				currentNode.setName(textAnnotation);
			} else if (type == NodeType.GROUP) {
				String groupName = attr.getValue("Group");
				currentNode.setName(groupName);
			}
			currentNode.setType(type);
			currentNode.setId(new IdDesc(id));
		} else if (StringUtils.equals(name, "/Package/Artifacts/Artifact/DataObject")) {
			String objName = attr.getValue("Name");
			String state = attr.getValue("State");
			currentNode.setName(objName);
			currentNode.setObjectState(state);
		} else if (name.matches("/Package/Artifacts/Artifact/NodeGraphicsInfos/NodeGraphicsInfo")) {
			int height = Integer.parseInt(attr.getValue("Height"));
			int width = Integer.parseInt(attr.getValue("Width"));
			currentNode.setGraphicsInfo(new GraphicsInfo(0,0,width, height));
		} else if (name.matches("/Package/Artifacts/Artifact/NodeGraphicsInfos/NodeGraphicsInfo/Coordinates")) {
			int x = Integer.parseInt(attr.getValue("XCoordinate"));
			int y = Integer.parseInt(attr.getValue("YCoordinate"));
			currentNode.getGraphicsInfo().setX(x);
			currentNode.getGraphicsInfo().setY(y);
		}
	}

	@Override
	public void endElement(String name, String characters) {
		if (StringUtils.equals(name, "/Package/Artifacts/Artifact")) {
			nodes.put(currentNode.getId().toString(), currentNode);
		}
	}

	@Override
	public Map<String, Node> getNodes() {
		return nodes;
	}

	@Override
	public Map<Route, Transition> getTransitions() {
		return null;
	}

	@Override
	public Map<String, Node> getPools() {
		return null;
	}
}